﻿using KwaiXiaoDian.Entity.VO.User;
using KwaiXiaoDian.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SSharing.Frameworks.NetCore.Common.Consts;
using SSharing.Frameworks.NetCore.Common.Extends;
using SSharing.Frameworks.NetCore.Common.Helpers;
using SSharing.Frameworks.NetCore.Common.Results;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Text.RegularExpressions;

namespace KwaiXiaoDian.OpenApi.Controllers
{
    /// <summary>
    /// 帐户
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly IUserService _userService;
        private readonly IOptions<JwtSettings> _jwtSettings;

        public AccountController(IUserService userService
            , IOptions<JwtSettings> jwtSettings)
        {
            _userService = userService;
            _jwtSettings = jwtSettings;
        }

        /// <summary>
        /// 获取Access Token
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("getaccesstoken")]
        public ActionResult<ApiResult<string>> GetAccessToken(GetAccessTokenRequest request)
        {
            //校验用户名和密码是否正确
            //生成并返回access token
            var apiResult = new ApiResult<string>();
            var now = DateTime.Now;

            //参数校验
            if (request == null)
            {
                request = new GetAccessTokenRequest();
            }
            if (request.PhoneNumber.IsNullOrEmpty())
            {
                apiResult.ErrorMessage = "手机号不能为空！";
                return apiResult;
            }
            var isValidPhoneNumber = RegexHelper.IsMobileNum(request.PhoneNumber);
            if (!isValidPhoneNumber)
            {
                apiResult.ErrorMessage = "手机号格式不合法！";
                return apiResult;
            }
            if (request.Passwd.IsNullOrEmpty())
            {
                apiResult.ErrorMessage = "密码不能为空！";
                return apiResult;
            }

            //校验用户名和密码是否正确
            var user = _userService.Get(p => p.PhoneNumber == request.PhoneNumber && p.Passwd == request.Passwd.ToMD5With32bit() && p.IsEnabled == Entity.Common.Enums.IsEnabledType.Y.ToString()).FirstOrDefault();
            if (user == null)
            {
                apiResult.ErrorCode = Entity.Common.Consts.ErrorCodes.A0103;
                apiResult.ErrorMessage = "手机号或密码错误，请重试！";
                return apiResult;
            }

            //生成access token
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));
            List<string> roles = new List<string>();
            if (!user.Role.IsNullOrEmpty())
            {
                roles = user.Role.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
                foreach (var item in roles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, item));
                }
            }
            string key = _jwtSettings.Value.SecKey;
            DateTime expires = now.AddMinutes(_jwtSettings.Value.ExpireMinutes);

            byte[] secBytes = Encoding.UTF8.GetBytes(key);
            var secKey = new SymmetricSecurityKey(secBytes);
            var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature);
            var tokenDescriptor = new JwtSecurityToken(claims: claims, expires: expires, signingCredentials: credentials);
            string jwtToken = new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
            apiResult.Data = jwtToken;
            apiResult.ErrorCode = ErrorCodeConst.OK;

            return apiResult;
        }

    }
}
